package com.easy.modules.sysmgr.service.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.dbutils.handlers.MapHandler;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.easy.common.dao.DBUtilsHelper;
import com.easy.common.dao.IBaseDao;
import com.easy.common.util.BeanUtils;
import com.easy.common.util.string.ClobUtil;
import com.easy.common.web.page.Msg;
import com.easy.modules.sysmgr.entity.CompanyEntity;
import com.easy.modules.sysmgr.service.CompanyServiceI;
import com.easy.modules.sysmgr.web.form.CompanyForm;

@Service
@Transactional
public class CompanyServiceImpl implements CompanyServiceI {

	@Autowired
	private IBaseDao<CompanyEntity> basedaoCompany;
	
	@Autowired
	private DBUtilsHelper dbUtil ;

	@Override
	public Msg save(CompanyForm form) {
		try {
			CompanyEntity entity = new CompanyEntity();
			BeanUtils.copyNotNullProperties(form, entity, new String[]{"remark"});
			entity.setRemark(ClobUtil.getClob(form.getRemark())) ;
			entity.setCreated(new Date()) ; 

			if (form.getPid() != null && !"".equalsIgnoreCase(form.getPid())) {
				entity.setCompany(this.basedaoCompany.load(CompanyEntity.class, form.getPid()));
			}
			this.basedaoCompany.add(entity);
			
			return new Msg(true, "创建成功!");
		} catch (BeansException e) {
			return new Msg(false, "创建失败！") ;
		}
	}

	@Override
	public Msg delete(String id) {
		try {
			CompanyEntity t = this.basedaoCompany.load(CompanyEntity.class, id);
			del(t);
			return new Msg(true, "删除成功！") ;
		} catch (BeansException e) {
			return new Msg(false, "删除失败！") ;
		}
	}
	
	private void del(CompanyEntity entity) {
		if (entity.getCompanys() != null && entity.getCompanys().size() > 0) {
			for (CompanyEntity r : entity.getCompanys()) {
				del(r);
			}
		}
		this.basedaoCompany.delete(CompanyEntity.class, entity.getId());
	}

	@Override
	public Msg edit(CompanyForm form) {
		try {
			CompanyEntity entity = this.basedaoCompany.load(CompanyEntity.class, form.getId());
			
			if(entity != null) {
				BeanUtils.copyNotNullProperties(form, entity, new String[]{"remark"});
				entity.setModifyDate(new Date()) ;
				entity.setRemark(ClobUtil.getClob(form.getRemark())) ;
				
				if (form.getPid() != null && !form.getPid().equalsIgnoreCase("")) {
					entity.setCompany(basedaoCompany.load(CompanyEntity.class, form.getPid()));
				}
				if (form.getPid() != null && !form.getPid().equalsIgnoreCase("")) {
					CompanyEntity pt = basedaoCompany.load(CompanyEntity.class, form.getPid());
					isChildren(entity, pt);
					entity.setCompany(pt);
				} else {
					entity.setCompany(null);
				}
			}
			
			return new Msg(true, "编辑成功！") ;
		} catch (BeansException e) {
			return new Msg(false, "编辑失败！") ;
		}
	}
	
	/**
	 * 判断是否是将当前节点修改到当前节点的子节点
	 * @param entity 当前节点
	 * @param pt 要修改到的节点
	 * @return
	 */
	private boolean isChildren(CompanyEntity entity, CompanyEntity pt) {
		if (pt != null && pt.getCompany() != null) {
			if (pt.getCompany().getId().equalsIgnoreCase(entity.getId())) {
				pt.setCompany(null);
				return true;
			} else {
				return isChildren(entity, pt.getCompany());
			}
		}
		return false;
	}
	

	@Override
	public CompanyForm get(String id) {

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", id);
		CompanyEntity entity = (CompanyEntity) this.basedaoCompany.queryObject("select t from CompanyEntity t where t.id = :id", params);
		
		CompanyForm form = new CompanyForm();
		
		if(null != entity) {
			BeanUtils.copyNotNullProperties(entity, form, new String[]{"remark"});
			form.setRemark(ClobUtil.getString(entity.getRemark())) ;
			
			if (entity.getCompany() != null) {
				form.setPid(entity.getCompany().getId());
			}
		}
		return form ;
	}

	@Override
	public List<CompanyForm> tree(CompanyForm form) {
		String hql = "select t from CompanyEntity t where t.company is null" ;
		
		List<CompanyEntity> entitys = this.basedaoCompany.list(hql) ;
		
		List<CompanyForm> companysform = new ArrayList<CompanyForm>() ;
		
		for (CompanyEntity companyEntity : entitys) {
			companysform.add(recursiveNode(companyEntity)) ;
		}
		return companysform ;
	}
	
	public CompanyForm recursiveNode(CompanyEntity entity) {
		CompanyForm mf = new CompanyForm() ;
		BeanUtils.copyNotNullProperties(entity, mf, new String[]{"remark"}) ;
		
		mf.setRemark(ClobUtil.getString(entity.getRemark())) ;
		
		mf.setText(entity.getName()) ;	
		
		if(null != entity.getCompanys() && entity.getCompanys().size() > 0) {
			mf.setState("closed") ;
			
			Set<CompanyEntity> rs = entity.getCompanys() ;
			List<CompanyForm> children = new ArrayList<CompanyForm>();
			for (CompanyEntity companyEntity : rs) {
				
				CompanyForm tn = recursiveNode(companyEntity) ;
				BeanUtils.copyNotNullProperties(companyEntity ,tn, new String[]{"remark"}) ;
				tn.setRemark(ClobUtil.getString(companyEntity.getRemark())) ;
				children.add(tn);
			}
			
			mf.setChildren(children) ;
			mf.setState("open");
		}
		return mf ;
	}

	@Override
	public Map<String, Object> totalMemberNum(CompanyForm form) {
		Map<String, Object> map = new HashMap<String,Object>() ;
		
		try {
			/*
			StringBuffer sql = new StringBuffer() ;
			sql.append(" SELECT") ;
			sql.append(" d.name, o.name,") ;
			sql.append(" (SELECT count(*) FROM easy_sysmgr_user u WHERE u.DEPT_ID=d.id) memberTotal,") ;
			sql.append(" (SELECT count(*) FROM easy_sysmgr_user u WHERE u.DEPT_ID=d.id and u.sex='男') male,") ;
			sql.append(" (SELECT count(*) FROM easy_sysmgr_user u WHERE u.DEPT_ID=d.id and u.sex='女') female") ;
			sql.append(" FROM easy_sysmgr_dept d, easy_sysmgr_company o") ;
			sql.append(" WHERE d.company_id='"+form.getId()+"'") ;
			*/
			
			StringBuffer sql = new StringBuffer() ;
			sql.append(" SELECT") ;
			sql.append(" count(u.id) totalMember") ;
			sql.append(" FROM easy_sysmgr_user u") ;
			sql.append(" WHERE u.company_id='"+form.getId()+"'") ;
			
			map = this.dbUtil.getRunner().query(sql.toString(), new MapHandler()) ;
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return map;
	}

}
